﻿using IP2Region.Net.Abstractions;
using IP2Region.Net.XDB;
using System.Text.RegularExpressions;

namespace Agile.Infra.Core.Agile.Helper;

public static class IpHelper
{
    private static readonly ISearcher _searcher = null;
    static IpHelper()
    {
        var dbPath = Path.Combine(AppContext.BaseDirectory, "Data", "ip2region.xdb");
        _searcher = new Searcher(CachePolicy.Content, dbPath);
    }
    public static string IpToAddress(this string @this)
    {
        if (@this.IsNullOrWhiteSpace()) return @this;

        string addrStr = "未知";
        try
        {
            //有效的IPv4地址 
            if (Regex.IsMatch(@this, RegexPattern.IPAddress))
            {
                var ipInfo = _searcher.Search(@this);
                //var ipInfo = IpTool.Search(@this);
                //addrStr = ipInfo.City == "0" ? $"{ipInfo.Country}" : $"{ipInfo.Province}{ipInfo.City}";
                if (!string.IsNullOrWhiteSpace(ipInfo))
                {
                    var arr = ipInfo.Split('|', StringSplitOptions.RemoveEmptyEntries).Where(a => a != "0");
                    if (arr.Count() > 0)
                    {
                        addrStr = string.Join(",", arr.Distinct());
                    }
                }
            }
        }
        catch (Exception) { }

        return addrStr;
    }
}
